package com.yn.module.material.utils.xls;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 定义策略工厂，将注解中的策略信息在系统启动后写入到工厂中
 * @author: zq
 * @create: 2021-07-12 14:11
 * @since: 1.0.0
 * @copyright (C), 2020, 北京望海康信科技有限公司.All rights reserved.
 */

@Component
public class ExcelStrategyFactory implements ApplicationContextAware {
    public static String EXCEL_PREFIX = "xls:";

    /**
     * 根据传入的ExcelInfo信息获取Excel导入导出的相关信息
     */
    public static ExcelEntity getExcelImportExportInfo(String type) {
        return EXCEL_FACTORY.get(EXCEL_PREFIX + type);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // excel相关
        Map<String, Object> importMap = applicationContext
                .getBeansWithAnnotation(ExcelOperation.class);
        for (Map.Entry<String, Object> entry : importMap.entrySet()) {
            Class<ExcelService> excelHandlerClass = (Class<ExcelService>) entry.getValue().getClass();
            ExcelOperation strategy = excelHandlerClass.getAnnotation(ExcelOperation.class);

            ExcelEntity entity = new ExcelEntity();
            entity.setImportClz(strategy.importClz());
            entity.setSheetIndex(strategy.sheetIndex());
            entity.setImportHeaderLines(strategy.importHeaderLines());
            entity.setSvc(applicationContext.getBean(excelHandlerClass));
            entity.setType(strategy.type());
            EXCEL_FACTORY.put(EXCEL_PREFIX + strategy.type().getValue(), entity);

        }
    }

    /**
     * 定义存放Excel导入/导出信息相关的map
     * object[]中内容：导入的excel的sheet名称，导入的类对象，导入的标题行数，导出的Excel名称，导出的标题行数,对应的ImportService
     */
    private static Map<String, ExcelEntity> EXCEL_FACTORY = new HashMap<>();

}
